import pandas as pd
from datetime import datetime

import numpy as np
from datetime import date
from iotdb.Session import Session
from iotdb.utils.BitMap import BitMap
from iotdb.utils.IoTDBConstants import TSDataType, TSEncoding, Compressor
from iotdb.utils.Tablet import Tablet
from iotdb.utils.NumpyTablet import NumpyTablet

import pandas as pd
from datetime import datetime, timedelta
import os


def process_csv_files(input_folder, output_folder):
    # Get list of CSV files in the input folder
    csv_files = [f for f in os.listdir(input_folder) if f.endswith('.csv')]
    csv_files.sort()  # Ensure files are processed in order

    start_time = datetime(2024, 1, 1, 8, 33, 1)

    for i, csv_file in enumerate(csv_files):
        input_file = os.path.join(input_folder, csv_file)
        output_file = os.path.join(output_folder, csv_file)

        # Read the CSV file
        df = pd.read_csv(input_file, header=None)
        # 提取第一行的前三列
        hour = df.iloc[0, 0]  # 第一列（时）
        minute = df.iloc[0, 1]  # 第二列（分）
        second = df.iloc[0, 2]  # 第三列（秒）
        start_time = datetime(2024, 1, 1, hour=hour, minute=minute, second=second)

        # Drop the first four columns
        df = df.iloc[:, 4:]

        # Insert the Time column with the desired format
        df.insert(0, 'Time', pd.date_range(start=start_time, periods=len(df), freq='ms'))

        # 将时间字符串转换为 datetime 类型
        # time_dt = pd.to_datetime(pd['Time'], format='%Y-%m-%d %H:%M:%S.%f')

        # 将时间转换为 Unix 时间戳（单位为秒）
        df['Time'] = df['Time'].astype('int64') // 10**6

        df.columns = ['Time', 'root.phm2012.no1.Bearing1_3.Horizontal', 'root.phm2012.no1.Bearing1_3.vertical']  # 根据列数修改列名

        # Save the processed DataFrame to a new CSV file
        df.to_csv(output_file, index=False)


def merge_csv_files(input_folder, output_file):
    # Get list of CSV files in the input folder
    csv_files = [f for f in os.listdir(input_folder) if f.endswith('.csv')]
    csv_files.sort()  # Ensure files are processed in order

    merged_df = pd.DataFrame()

    for csv_file in csv_files:
        input_file = os.path.join(input_folder, csv_file)

        # Read the CSV file
        df = pd.read_csv(input_file)

        # Append the DataFrame to the merged DataFrame
        merged_df = pd.concat([merged_df, df], ignore_index=True)

    # Save the merged DataFrame to a new CSV file
    merged_df.to_csv(output_file, index=False)


# Example usage
input_folder = 'D:/desktop/rul_system/Bearing1_3'
output_folder = 'D:/desktop/rul_system/output_data'
process_csv_files(input_folder, output_folder)
# merge_csv_files(output_folder, 'D:/desktop/rul_system/merged_data_2000_2375.csv')
# # creating session connection.
# ip = "127.0.0.1"
# port_ = "6667"
# username_ = "root"
# password_ = "root"
# # session = Session(ip, port_, username_, password_, fetch_size=1024, zone_id="UTC+8", enable_redirection=True)
# session = Session.init_from_node_urls(
#     node_urls=["127.0.0.1:6667", "127.0.0.1:6668", "127.0.0.1:6669"],
#     user="root",
#     password="root",
#     fetch_size=1024,
#     zone_id="UTC+8",
#     enable_redirection=True,
# )
# session.open(False)
